#include "serial.h"
#include "codec.h"
#include "bsp/uart.h"
#include "os/os.h"
#include "utils/logger.h"

static u32 serial_task(void *param) {
    serial_t *serial = (serial_t *)param;
    uart_tx_poll(serial->hw_id);
    uart_rx_poll(serial->hw_id);
    return 0;
}

void serial_init(serial_t *serial) {
    serial->dec.call_back = serial->rx_handler;
    serial->dec.hw_id = serial->enc.hw_id = serial->hw_id;
    codec_init_decoder(&serial->dec);
    codec_init_encoder(&serial->enc);
    uart_init(serial->hw_id, serial->rate, codec_decoder_callback, (void *)&serial->dec);
    uart_set_dma_queue(serial->hw_id, encoder_get_queue(&serial->enc));
    os_task_create(serial_task, serial);
}

int serial_send_data(serial_t *serial, u8 *buff, int len) {
    codec_encode_message(&serial->enc, NULL, 0, buff, len);
	if (!is_in_irq_context()) {
		uart_tx_poll(serial->hw_id);
	}
    return len;
}

int serial_send_frame(serial_t *serial, u32 id, u8 *buff, int len) {
    u8 head[5] = {38, 0, 0, 0, 0};
    memcpy(head+1, &id, sizeof(id));
    codec_encode_message(&serial->enc, head, sizeof(head), buff, len);
	if (!is_in_irq_context()) {
		uart_tx_poll(serial->hw_id);
	}
    return len;
}

